package com.video.utils;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.*;
import java.io.File;
import java.util.List;

public class ViewUtils {
    public static void enableDragAndDrop(Component component) {
        new DropTarget(component, new DropTargetListener() {
            @Override
            public void dragEnter(DropTargetDragEvent dtde) {

            }

            @Override
            public void dragOver(DropTargetDragEvent dtde) {

            }

            @Override
            public void dropActionChanged(DropTargetDragEvent dtde) {

            }

            @Override
            public void dragExit(DropTargetEvent dte) {

            }

            @Override
            public void drop(DropTargetDropEvent target) {
                target.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
                try {
                    Transferable transferable = target.getTransferable();
                    if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                        List<File> fileList = (List<File>) transferable.getTransferData(DataFlavor.javaFileListFlavor);
                        if (!fileList.isEmpty()) {
                            File file = fileList.get(0);
                            DropTarget dropTarget = (DropTarget) target.getSource();
                            JTextField field = (JTextField) dropTarget.getComponent();
                            field.setText(file.getAbsolutePath());
                            target.dropComplete(true);
                        }
                    } else {
                        target.rejectDrop();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    target.dropComplete(false);
                }
            }
        });
    }
}
